package com.lingyi.schedulemanager.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lingyi.schedulemanager.pojo.Schedule;
import com.lingyi.schedulemanager.pojo.TripMode;
import com.lingyi.schedulemanager.service.ScheduleService;
import com.lingyi.schedulemanager.service.TripModeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
public class ScheduleController {
    @Autowired
    private ScheduleService scheduleService;
    @Autowired
    private TripModeService tripModeService;

    @GetMapping("/list")
    public String list(Model model, Schedule schedule,@RequestParam(defaultValue = "1") Integer pageNo) {

        QueryWrapper<Schedule> queryWrapper = new QueryWrapper<>();

        if (schedule.getTripModeId() != null && schedule.getTripModeId() > 0) {
            queryWrapper.eq("trip_mode_id", schedule.getTripModeId());
        }


//        List<Schedule> scheduleList = scheduleService.list(queryWrapper);

        List<TripMode> tripModeList = tripModeService.list();

        IPage<Schedule> page = scheduleService.page(new Page<>(pageNo, 3), queryWrapper);
        long totalCount = page.getTotal();
        long totalPages = page.getPages();
        long pageSize = page.getSize();

        List<Schedule> scheduleList = page.getRecords();


        model.addAttribute("tripModeList", tripModeList);
        model.addAttribute("list", scheduleList);
        model.addAttribute("totalCount", totalCount);
        model.addAttribute("totalPages", totalPages);
        model.addAttribute("pageNo", pageNo);
        model.addAttribute("pageSize", pageSize);

        return "list";
    }

    @GetMapping("/toAdd")
    public String toAdd(Model model) {
        List<TripMode> tripModes = tripModeService.list();

        model.addAttribute("tripModes", tripModes);

        return "add";
    }

    @PostMapping("/add")
    public String add(Schedule schedule) {

        schedule.setStatus(0);
        boolean result = scheduleService.save(schedule);

        if (result) {
            return "redirect:list";
        } else {
            return "error";
        }
    }

    @GetMapping("/update")
    public String update(Schedule schedule) {

        boolean result = scheduleService.updateByUpdate(schedule);

        if (result) {
            return "redirect:list";
        } else {
            return "error";
        }
    }
}
